﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

namespace Yubis.Data
{
    public class Setup
    {
        
        public Server SqlServer { get; set; }

        public string DatabaseName { get; set; }
        
        public Setup( string sqlServerName, string name)
        {
            DatabaseName = Yubis.Data.Properties.Settings.Default.DatabasePrefix + name;
            
            SqlServer = new Server(sqlServerName);
            SqlServer.ConnectionContext.Connect();
        }

        public Setup(string sqlServerName, string name, string username, string password)
        {

            DatabaseName = Yubis.Data.Properties.Settings.Default.DatabasePrefix + name;

            ServerConnection connection = new ServerConnection();

            connection.Password = password;
            connection.Login = username;
            connection.ServerInstance = sqlServerName;

            SqlServer = new Server(connection);
            SqlServer.ConnectionContext.Connect();
        }


        public void Run()
        {
            createDatabase();
            createTables();
        }

        public void DeleteDatabase()
        {

            SqlServer.KillDatabase( DatabaseName);
        }


        private void createDatabase()
        {
            Database database = new Database();
            database.Parent = SqlServer;
            database.Name = DatabaseName;
            database.Create();
        }

        private void createTables()
        {
            Database database = SqlServer.Databases[DatabaseName];

            Table fieldChoice = new Table(database,"Field_Choice");

            fieldChoice.Columns.Add(new Column(fieldChoice,"Id",DataType.UniqueIdentifier));
            fieldChoice.Columns.Add(new Column(fieldChoice, "Name", DataType.NVarChar(64)));
            fieldChoice.Indexes.Add(new Index(fieldChoice, "PK_Field_Choice"));
            fieldChoice.Indexes["PK_Field_Choice"].IndexKeyType = IndexKeyType.DriPrimaryKey;
            fieldChoice.Indexes["PK_Field_Choice"].IndexedColumns.Add(new IndexedColumn(fieldChoice.Indexes["PK_Field_Choice"], "Id"));

            fieldChoice.Create();
        
        }
    }
}
